import QtQuick 1.1
import QtWebKit 1.0
import Qt 4.7
import "js/dbmanager.js" as DB
import "js/twitter-oauth.js" as TWITTER_OAUTH
import "js/oauth.js" as OAUTH1


Item {
    id: twitterOauth

    property alias url : loginView.url


    property string nextState: "AuthDone"
    //    property string consumerKey: "eqE0YFNDqJZGBi3wjgYTgQ"
    //    property string consumerSecret: "O5U1Sfi3WcoAfILWotEdZQT5sJF5YBOIqFSSSfhxSdA"

    //authorization request properties
    property bool oauth_callback_confirmed

    //authorization access properties
    property string user_id: "";
    property string screen_name: "";
    property string oauth_token: "";
    property string oauth_token_secret : "";

    anchors.fill: parent
    Component.onCompleted: DB.checkToken();

    WebView {
        id: loginView
        visible: false
        anchors.fill: parent
        onUrlChanged: changeUrl(url)
    }

    onStateChanged: {
        if(state==DB.STATES.LOGIN){
            TWITTER_OAUTH.requestToken();
        }
    }

    states: [
        State {
            name: DB.STATES.LOGIN
            PropertyChanges {
                target: loginView
                visible: true
                url: TWITTER_OAUTH.oauth_data.authorizeUrl + "?oauth_token=" + oauth_token
            }
        },
        State {
            name: DB.STATES.AUTHDONE
            PropertyChanges {
                target: loginView
                visible: false
                opacity: 0
            }
            PropertyChanges {
                target: parent
                state: nextState
            }
        }
    ]

    function changeUrl(url) {
        if(url!= ""){

            if(debug) console.log("\turl: " + url.toString());
            var authorized = false;
            var mUrl = url.toString();
            var oauth_verifier = "";
            var regexp = "oauth_verifier";
            var ret = url.toString().search(regexp);
            if(ret > -1){
                var query = mUrl.substring(mUrl.indexOf('?') + 1);
                var vars = query.split("&");
                for (var i=0;i<vars.length;i++) {
                    var pair = vars[i].split("=");
                    if (pair[0] == "oauth_verifier") {
                        authorized = true;
                        oauth_verifier = pair[1];
                    }
                }
            }

            if (authorized) {
                if(debug) console.log("authorized: " + authorized);
                TWITTER_OAUTH.requestPermanentAcccesToken(oauth_verifier);
            }
        }
    }
}

